package request

import (
	"encoding/json"
	"time"

	"github.com/go-resty/resty/v2"
)

type RequestResult struct {
	Start         uint64
	End           uint64
	Cost          uint64
	ReceivedBytes uint64
	Code          int
	Content       string
	ErrMsg        string
	No            uint64
}

type HttpRequest struct {
	Client *resty.Client
}

func (c *HttpRequest) Init() {
	c.Client = resty.New().SetTimeout(time.Second * 30)
}

func (c *HttpRequest) Post(url string, body interface{}) *RequestResult {
	rst := &RequestResult{}
	byteBody, _ := json.Marshal(body)
	rst.Start = uint64(time.Now().UnixMilli())
	resp, err := c.Client.R().SetHeader("Content-Type", "application/json;charset=UTF-8").SetBody(byteBody).Post(url)
	rst.End = uint64(time.Now().UnixMilli())
	rst.Cost = rst.End - rst.Start
	if err != nil {
		rst.ErrMsg = err.Error()
		return rst
	}
	rst.Code = resp.StatusCode()
	rst.Content = string(resp.Body())
	rst.ReceivedBytes = uint64(resp.Size())
	return rst
}

func (c *HttpRequest) Get(url string) *RequestResult {
	rst := &RequestResult{}

	rst.Start = uint64(time.Now().UnixMilli())
	resp, err := c.Client.R().SetHeader("Content-Type", "application/json;charset=UTF-8").Get(url)
	rst.End = uint64(time.Now().UnixMilli())
	rst.Cost = rst.End - rst.Start
	if err != nil {
		rst.ErrMsg = err.Error()
		return rst
	}
	rst.Code = resp.StatusCode()
	rst.Content = string(resp.Body())
	rst.ReceivedBytes = uint64(resp.Size())
	return rst
}
